<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../res/layui/css/layui.css"  media="all">
  <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
  <legend>增加和修改</legend>
</fieldset>
 
<form class="layui-form" action="" lay-filter="example" id="newsForm">
	<input type='hidden' name='roleId' id='roleId'>
	<input type='hidden' name='userId' id='userId'>
  <div class="layui-form-item">
    <label class="layui-form-label">用户名</label>
    <div class="layui-input-block">
      <input type="text" name="userName" lay-verify="title" autocomplete="off" placeholder="请输入用户名" class="layui-input" id="userName">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">用户密码</label>
    <div class="layui-input-block">
      <input type="password" name="userPwd" lay-verify="pass" id="userPwd" placeholder="请输入密码" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">手机号</label>
    <div class="layui-input-block">
      <input type="text" name="userPhone" id="userPhone" lay-verify="title" autocomplete="off" placeholder="请输入手机号" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">邮箱</label>
    <div class="layui-input-block">
      <input type="text" name="userEmail" id="userEmail" lay-verify="title" autocomplete="off" placeholder="请输入邮箱" class="layui-input">
    </div>
  </div>
  
  <div class="layui-form-item">
    <label class="layui-form-label">职位</label>
    <div class="layui-input-block" id="checkBox">
    </div>
  </div>
  
  <div class="layui-form-item">
    <label class="layui-form-label">是否有效</label>
    <div class="layui-input-block">
      <input type="checkbox" name="userValidity" checked="" id="userValidity" lay-skin="switch" lay-text="有效|无效">
    </div>
  </div>
  <div class="layui-form-item">
  <label class="layui-form-label">上传图片</label>
  <div class="layui-input-block">
	  	<input type='file' id='userImgs' name='userImgs'>
	  	</div>
  </div>  
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
    </div>
  </div>
   
</form>
<script src="../res/layui/layui.js" charset="utf-8"></script>
<script src="../res/js/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../res/js/tools.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<script>
layui.use(['form', 'layedit', 'laydate','upload'], function(){
  var form = layui.form
  ,layer = layui.layer
  ,layedit = layui.layedit
  ,laydate = layui.laydate
  ,upload = layui.upload ;
  
  //日期
  laydate.render({
    elem: '#date'
  });
  laydate.render({
    elem: '#date1'
  });
  
  //创建一个编辑器
  var editIndex = layedit.build('LAY_demo_editor');
  //自定义验证规则
  form.verify({
    title: function(value){
      if(value.length < 2){
        return '标题至少得2个字符啊';
      }
    }
    ,pass: [
      /^[\S]{6,12}$/
      ,'密码必须6到12位，且不能出现空格'
    ]
    ,content: function(value){
      layedit.sync(editIndex);
    }
  });
  //监听提交
  form.on('submit(demo1)', function(data){
	  var id = "";
	  $("input[name='roleId']:checked").each(function(index,items){
			id+=$(this).val()+",";
	 });
    $("#roleId").val(id);
    var formData = new FormData(document.getElementById("newsForm"));
	//传输路径
	var url = "../User/insert.action";
	$.ajax({
		url:url,
		type:"post", // 传输类型
		data:formData, // 数据
		async:false, // 全局同步
		processData:false,
		contentType:false,
		dataType:"json",
		success:function(obj){
			if(obj.state==1){
				layer.msg(obj.msg,{
					icon:1,
				 	time:1000,
				 },function(){
					 var indexs = parent.layer.getFrameIndex(window.name);
					 parent.layer.close(indexs);
				 });
	    		return false ;
			}
		},
		error:function(e){
			alert("失败了");
		}
	}); 
	return false
  });
  //表单取值
  layui.$('#LAY-component-form-getval').on('click', function(){
    var data = form.val('example');
    alert(JSON.stringify(data));
  });
  var id = getQueryString("id");
  if(id!=null){
	  var url = "../User/findId.action";
		var data = {id:id};
		$.post(url,data,function(obj){
			var role = obj.roleId ;
			var ids = role.split(',');
			var url = '../Role/findAll.action';
			$.post(url,null,function(objs){
				$.each(objs,function(index,items){
					if(items.roleValidity==1){
						var j = 0;
						for (var i = 0; i < ids.length; i++) {
							if(items.roleId==ids[i]){
								j=1;
								break ;
							}
						}
						if(j==1){
							$("#checkBox").append('<input type = "checkbox" name="roleId" checked="checked" title="'+items.roleName+'" value="'+items.roleId+'">');
							form.render("checkbox");
						}else if(j==0){
							$("#checkBox").append('<input type="checkbox" name="roleId" title="'+items.roleName+'" value="'+items.roleId+'">');
							form.render("checkbox");
						}
					}
				})
			},'json')
			$("#userId").val(obj.userId);
			$("#userName").val(obj.userName);
			$("#userPwd").val(obj.userPwd);
			$("#userPhone").val(obj.userPhone);
			$("#userEmail").val(obj.userEmail);
			if(obj.userValidity=="有效"){
				 form.val('example', {
					"userValidity": true //开关状态
				})
			}else{
				form.val('example', {
				    "userValidity": false//开关状态
				})
			}
		},'json')
  }else{
	  var url = '../Role/findAll.action';
	  $.post(url,null,function(obj){
		  $.each(obj,function(index,items){
			  if(items.roleValidity==1){
				  $("#checkBox").append('<input type="checkbox" name="roleId" title="'+items.roleName+'" value="'+items.roleId+'">');
				  form.render("checkbox");
			  }
			  
		  })
	  },'json') 
  }
});
</script>
</body>
</html>